package me.lensfrex.vegetables.resopnse;

import me.lensfrex.vegetables.data.Vegetable;
import me.lensfrex.vegetables.exceptions.IllegalPageParamException;
import me.lensfrex.vegetables.exceptions.RequestPageTooLargeException;
import me.lensfrex.vegetables.exceptions.SourceDataWornException;
import me.lensfrex.vegetables.utils.IOUtils;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * 请求处理类，上层处理请求，主要为对返回数据的封装。
 * 由于功能简单，仅有处理分页数据
 */
public class ResponseProcessor {

    private final String sourceFilePath;

    /**
     * 初始化ResponseProcessor实例，并指定源数据文件的路径
     *
     * @param sourceFilePath 数据源文件路径
     */
    public ResponseProcessor(String sourceFilePath) {
        this.sourceFilePath = sourceFilePath;
    }

    /**
     * 从文件中读取并根据参数进行分页
     *
     * @param pageNum  页码（从1开始）
     * @param pageSize 每页结果的数量
     * @return UnityResponse<ArrayList < Vegetable>> 统一的响应类
     */
    public UnityResponse<ArrayList<Vegetable>> getListPage(int pageNum, int pageSize) {
        ResponseTool tools = new ResponseTool();
        try {
            LinkedList<String> sourceData = IOUtils.getListFromFile(sourceFilePath);

            LinkedList<Vegetable> allVegetables = tools.getAllVegetables(sourceData);

            ArrayList<Vegetable> result = new ArrayList<>(tools.getListPage(pageNum, pageSize, allVegetables));

            return ResponseGenerator.success(result);
        } catch (RequestPageTooLargeException e) {
            e.printStackTrace();
            return ResponseGenerator.error(ResultStatus.PAGE_OUT_OF_RANGE);
        } catch (IllegalPageParamException e) {
            e.printStackTrace();
            return ResponseGenerator.error(ResultStatus.PAGE_PARAM_WORN);
        } catch (SourceDataWornException e) {
            e.printStackTrace();
            return ResponseGenerator.error(ResultStatus.SOURCE_DATA_WORN);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseGenerator.error(ResultStatus.UNKNOWN_ERROR);
        }
    }
}
